//
//  LoginViewController.m
//  SocialEngine
//
//  Created by Tan NguyenBa on 8/30/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "LoginViewController.h"
#import "MainActivityViewController.h"
#import "KeyboardControl.h"
#import "WebServices.h"
#import "XMLParser.h"
#import "LoginState.h"
#import "defines.h"

@implementation LoginViewController
{
    BOOL keyboardVisible;
    CGPoint offset;
}

@synthesize scrollView;
@synthesize emailView;
@synthesize passwordView;
@synthesize txtUser;
@synthesize txtPass;

@synthesize activeField;
@synthesize btnLogin;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    scrollView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"bkg_login.png"]];
    emailView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"email.png"]];
    passwordView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"password.png"]];

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardDidShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidHide:)
                                                 name: UIKeyboardDidHideNotification
                                               object:nil];
    [scrollView setContentSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];
    keyboardVisible = NO;
}


- (void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self setScrollView:nil];
    [self setEmailView:nil];
    [self setPasswordView:nil];
    [self setTxtUser:nil];
    [self setTxtPass:nil];
    [self setBtnLogin:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void) keyboardDidShow:(NSNotification *) notif
{
    [KeyboardControl scrollFrameForTextBox:&keyboardVisible 
								withOffset:&offset 
							withScrollView:scrollView 
							 withTextField:activeField
						  withNotifacation:notif
								withHeight:self.view.frame.size.height];
}

-(void) keyboardDidHide: (NSNotification *)notif 
{
	
    [KeyboardControl backToOriginalSize:&keyboardVisible
							 withOffset:&offset 
							 withScroll:scrollView
							  withWidth:self.view.frame.size.width
							 withHeight:self.view.frame.size.height];	
    
}

- (BOOL) textFieldShouldReturn:(UITextField *) textField
{
	// the user pressed the "Done" button, so dismiss the keyboard
    if ([txtUser isFirstResponder]) {
        [txtPass becomeFirstResponder];
        return NO;
    }
    [textField resignFirstResponder];  
	return YES;
}

- (BOOL) textFieldShouldBeginEditing:(UITextField *) textField
{
	activeField = textField;    
	return YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction) loginAction 
{
    [self performSelectorInBackground:@selector(performLoginAction) withObject:nil];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	[self.view setUserInteractionEnabled:NO];	
}

- (void) performLoginAction 
{
    
    NSString *strUrlHttp = [NSString stringWithFormat:@"%@/user/login?ObjectType=email&ObjectId=%@&Password=%@&remember=1", 
                            URL_MAIN, txtUser.text, txtPass.text];
    NSLog(@"%@", strUrlHttp);
    NSData *responseData = [WebServices loginWithURL:strUrlHttp];
    
    if (responseData) {
        XMLParser *parse = [[XMLParser alloc] initXMLParser:PARSE_LOGIN];
		[parse doParse:responseData];
        
        if (parse.loginState.isLoginSuccess == YES)
        {
            [self performSelectorOnMainThread:@selector(changeToMainActivity:) withObject:parse.loginState waitUntilDone:NO];		
        }
        else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                                message:@"Login fail"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
        }
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
															message:@"Login fail"
														   delegate:nil
												  cancelButtonTitle:@"OK"
												  otherButtonTitles:nil];
		[alertView show];
    }
    
    
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	[self.view setUserInteractionEnabled:YES];
}

- (void) changeToMainActivity:(LoginState *) loginState
{
    UIStoryboard *myStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];    
    MainActivityViewController *mainActivity = (MainActivityViewController *)[myStoryboard instantiateViewControllerWithIdentifier:@"MainActivity"];
    [mainActivity setUserInfo:loginState];
    [self presentModalViewController:mainActivity animated:YES];
    // [self.navigationController pushViewController:mainActivity animated:YES];
}

@end
